package com.topcheer.provider.auth.jwt;

import com.topcheer.common.auth.jwt.JwtHelper;
import com.topcheer.common.auth.jwt.RsaKeyHelper;
import com.topcheer.common.auth.user.JwtUser;
import com.topcheer.common.base.CommonConstants;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xutao
 * @Package com.example.baseline.rbac.user
 * @Description: ${todo}
 * @date 2020/3/30 11:00
 */
@Data
@ConfigurationProperties(prefix = "jwt")
@Component
@Slf4j
public class JwtTokenUtil {

    private String secret;

    // 过期时间 毫秒
    private Long expiration;

    private String header;

    private String tokenHeader;

    private Map<String, byte[]> keyMap = new ConcurrentHashMap<>(2);

    public byte[] getKey(String secret,String key) throws IOException, NoSuchAlgorithmException {
        if(keyMap.get(key) == null){
            keyMap.putAll(RsaKeyHelper.generateKey(secret));
        }
        return keyMap.get(key);
    }

    public byte[] getKey(String key) throws IOException, NoSuchAlgorithmException {
        if(keyMap.get(key) == null){
            keyMap.putAll(RsaKeyHelper.generateKey(secret));
        }
        return keyMap.get(key);
    }

    public String generateToken(String userName) throws IOException, NoSuchAlgorithmException {
        return JwtHelper.generateToken(userName,getKey(secret, CommonConstants.USER_PRI_KEY),expiration);
    }

    public String getUsernameFromToken(String token) throws IOException, NoSuchAlgorithmException {
        return JwtHelper.getUsernameFromToken(token,getKey(secret,CommonConstants.USER_PUB_KEY));
    }

    public Boolean validateToken(String token, JwtUser jwtUser) throws IOException, NoSuchAlgorithmException {
        return JwtHelper.validateToken(token, jwtUser,getKey(secret,CommonConstants.USER_PUB_KEY));
    }
}
